package com.ctc.lottery.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ctc.lottery.entity.Member;
import com.ctc.lottery.service.MemberService;
import com.ctc.lottery.vo.MemberVo;
import com.ctc.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ctc
 */
@Api(tags = "现场抽奖")
@RestController
@RequestMapping(value = "sys/lottery")
@Slf4j
public class SceneController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberService memberService;

    @ApiOperation(value = "现场抽奖:查看参加抽奖人")
    @RequestMapping(value = "/getLotteryPerson", method = RequestMethod.GET)
    public R getLotteryPerson() {
        String key = "lottery-"+ LocalDate.now();
        Set<String> idSet = redisTemplate.opsForSet().members(key);
        List<Member> members = new ArrayList<>();
        if (idSet!=null && idSet.size()!=0) {
            members = memberService.listByIds(idSet);
        }

        return R.ok().put("data",members);
    }

    @ApiOperation(value = "现场抽奖:开始抽奖")
    @RequestMapping(value = "/StartLottery", method = RequestMethod.GET)
    public R startLottery(int count) {
        if (count<1){
            return R.error(402,"抽奖人数要大于1");
        }
        String key = "lottery-"+LocalDate.now();
        List<String> idList = new ArrayList<>();
        Long size = redisTemplate.opsForSet().size(key);
        while (count-->0 && size!=null && size != 0){
            idList.add((String) redisTemplate.opsForSet().pop(key));
        }
        List<Member> memberList = memberService.listByIds(idList);
        return R.ok().put("data",memberList);
    }

    @ApiOperation(value = "现场抽奖:在抽奖中加入所有会员")
    @RequestMapping(value = "/addAllMenber", method = RequestMethod.GET)
    public R addAllMenber() {
        List<Member> members = memberService.list();

        Object[] memberIdsObjest = members.stream().map(Member::getId).distinct().toArray();
        String[] memberIds = new String[memberIdsObjest.length];
        for (int i = 0; i < memberIds.length; i++) {
            memberIds[i] = (String) memberIdsObjest[i];
        }

        String key = "lottery-"+ LocalDate.now();
        redisTemplate.opsForSet().add(key,memberIds);
        redisTemplate.expire(key, 8, TimeUnit.HOURS);

        return R.ok().put("data",members);
    }
}
